package com.huluobo.kotlinim1907a

import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.media.SoundPool
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.multidex.MultiDex
import cn.bmob.v3.Bmob
import com.huluobo.kotlinim1907a.adapter.EMMessageListenerAdapter
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMOptions

/**
 * Created by lc on 2022/1/11.
 */
class IMApplication : Application() {
    companion object {
        lateinit var instance: IMApplication
        //因为伴生函数类似静态代码块,在类的初始化时调用
        //也就是说会在onCreate之前调用,这样肯定会产生空指针
        //使用lateinit,则在onCreate之后会创建实例
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    val soundPool: SoundPool = SoundPool.Builder().setMaxStreams(10).build()

    val duan by lazy {
        soundPool.load(instance, R.raw.duan, 0)
    }

    val yulu by lazy {
        soundPool.load(instance, R.raw.yulu, 0)
    }

    private val messageListener = object : EMMessageListenerAdapter() {
        override fun onMessageReceived(messages: MutableList<EMMessage>?) {
            //判断当前应用在前台或者后台
            if (isForeground()) {
                soundPool.play(duan, 1f, 1f, 0, 0, 1f)
            } else {
                soundPool.play(yulu, 1f, 1f, 0, 0, 1f)
            }
        }
    }

    //判断当前app是否在前台活跃
    private fun isForeground(): Boolean {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (runningAppProcess in activityManager.runningAppProcesses) {
            if (runningAppProcess.processName == packageName) {
                //找到了app的进程
                //判断当前app运行的关键级是否等于处于前台位置的关键级
                return runningAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
            }
        }
        return false
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        MultiDex.install(this)//解除65535方法数量限制
        //环信的初始化
        EMClient.getInstance().init(applicationContext, EMOptions())
        //在做打包混淆时,关闭debug模式,避免小号不必要的资源
        EMClient.getInstance().setDebugMode(BuildConfig.DEBUG)
        //Bmob初始化
        Bmob.initialize(this, "48cebb20284cdd7671bb57aa545e395d")

        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        soundPool.play(duan, 1f, 1f, 0, 0, 1f)
        soundPool.play(yulu, 1f, 1f, 0, 0, 1f)

    }
}